package dbinit;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.attribute.model.AttributeValue;
import core.util.HibernateCoreUtil;

public class InitAttributeValue 
{
	
	public static AttributeValue getAttributeValueByValue(String stringValue)
	{
		AttributeValue av = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			av = (AttributeValue) session.createCriteria(AttributeValue.class).add(Restrictions.eq("stringValue", stringValue)).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return av ;
	}
	public static AttributeValue getAttributeValueByUuid(Long uuid)
	{
		AttributeValue av = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				av = (AttributeValue) session.get(AttributeValue.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return av ;
	}
	public static Long doinit(String stringValue, String attributeType)
	{
		AttributeValue av = getAttributeValueByValue(stringValue) ;
		Long uuid = null;
		if(av == null)
		{
			av = new AttributeValue();
		}
		av.setStringValue(stringValue);
		av.setLabel(stringValue.toUpperCase());
		av.setAttributeType(attributeType);
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			session.saveOrUpdate(av);
			uuid = av.getUuid();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		
		return uuid ;
	}
}
